import router from "./index";
import config from "@/enum/setting";
import store from "@/store";
import { getToken } from "@/utils/token";
import { getLoginMenus } from "@/api/sysMenu";
import { resolveRouter } from "@/store/modules/permission";
// 页面白名单

const whiteList = ["/login"];

router.beforeEach((to, from, next) => {
  // to and from are both route objects. must call `next`.
  console.log("=====路由前置=====");
  // 设置标题
  if (to.meta.title) {
    document.title = to.meta.title + " - " + config.title;
  }
  // 判断token
  if (getToken()) {
    // 已登录且要跳转的页面是登录页
    if (to.path === "/login") {
      next({ path: "/home" });
    } else {
      // 判断是否拉取用户信息
      if (store.getters.roles.length === 0) {
        // 装载客户信息
        store.dispatch("saveUserCache").then((res) => {
          console.log("用户信息装载完成", store.getters.roles);
          getRouterListResult().then((res) => {
            console.log("路由等待装载", store.getters.routers);
            for (let routeEle of store.getters.routers) {
              router.addRoute(routeEle);
            }
            router.isReady();
            console.log("路由装载完毕", router.getRoutes());
            if(to.matched.length==1){
              next(to.path)
            }else{
              next({ ...to, replace: true });
            }
          });
        });
      } else {
        next();
      }
    }
  } else {
    // 判断是否属于免登录白名单
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      // 否则全部重定向到登录页
      next(`/login?redirect=${to.fullPath}`);
    }
  }
});



/**
 *
 * @returns 调用接口获取路由数据并解析
 *
 */
export function getRouterListResult() {
  return new Promise((resolve, reject) => {
    getLoginMenus().then((res) => {
      if (res.state) {
        let menus = res.data;
        let routerList = resolveRouter(menus);
        let routes = resolveRoutes(routerList);
        store.dispatch("GenerateRoutes", routes).then((res) => {
          resolve(routes);
          return routes;
        });
      } else {
        let routerList = [];
        store.dispatch("GenerateRoutes", routerList).then((res) => {
          resolve(routerList);
          return routerList;
        });
      }
    });
  });
}

/**
 *
 * @param {解析路由信息} routerList
 * @returns
 */
function resolveRoutes(routerList) {
  let resolveMenus = [];
  routerList.forEach((router) => {
    if (
      router.path !== "/" &&
      router.path !== "/login" &&
      router.path !== "/:pathMatch(.*)*"
    ) {
      if (router.children) {
        let xa = {
          component: router.component,
          name: router.name,
          path: router.path,
          children: router.children,
        };
        resolveMenus.push(xa);
        let renewList = resolveRoutes(router.children);
        if (renewList.length >= 1) {
          resolveMenus.forEach((value) => {
            if (value.path === router.path) {
              value.children = [...renewList];
            }
          });
        }
      } else {
        let xa = {
          component: router.component,
          name: router.name,
          path: router.path,
          children: [],
        };
        resolveMenus.push(xa);
      }
    }
  });
  // 过滤一下 ‘/’ '/login'
  return resolveMenus;
}
